package com.liuwei.spring.cloud.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.liuwei.spring.cloud.framework.dto.Result;
import com.liuwei.spring.cloud.common.enums.I18nEnum;
import com.liuwei.spring.cloud.common.utils.Reflects;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author : evan.liu
 * @version V1.0
 * @Description: TODO
 * @date Date : 2022年04月30日 11:38 下午
 */
@Slf4j
@RestController
@RequestMapping("/api")
@Tag(name = "Enums 枚举类型")
public class EnumsController {

    String scan = "com.liuwei.spring.cloud";

    @GetMapping("/enums")
    public Result<String> enums() throws Exception {
        Set<Class<?>> classes = Reflects.getSubClass(scan, Enum.class);
        Map<String,List<JsonNode>> result = new HashMap<>(16);
        if (CollectionUtils.isNotEmpty(classes)) {
            // 遍历所有的枚举类
            classes.stream().forEach(x -> {
                String name = x.getSimpleName();
                Field[] fields = x.getFields();
                Method[] methods = x.getMethods();
                try {
                    // 所有枚举类需实现 IBaseEnum
                    I18nEnum[] constants = (I18nEnum[]) x.getEnumConstants();
                    List<JsonNode> info = new ArrayList<>();
                    Arrays.stream(constants).forEach(v->{
                        ObjectNode jInfo = JsonNodeFactory.instance.objectNode();
                        jInfo.put("ordinal",v.ordinal());
                        jInfo.put("name",v.name());
                        jInfo.put("group",v.getGroup());
                        jInfo.put("code",v.getCode());
                        jInfo.put("desc",v.getMessage());
                        info.add(jInfo);
                    });
                    result.put(name, info);
                } catch (Exception e) {
                    log.error("枚举类: {} 未实现 IBaseEnum 接口",name);
                }
            });
        }
        return Result.success(result);
    }

}
